package com.eva.api.common;

import com.eva.api.BaseController;
import com.eva.core.annotation.trace.Trace;
import io.swagger.annotations.Api;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Api(tags = "本地文件接口")
@Trace(exclude = true)
@RestController
@RequestMapping("/common/local/file")
public class LocalFileController extends BaseController {

    /**
     * 下载本地文件
     */
    @GetMapping("/download")
    public void download (@RequestParam(name = "path") String path, @RequestParam(required = false) String name, HttpServletResponse response) throws IOException {
        ClassPathResource resource = new ClassPathResource("static/" + path);
        InputStream is = resource.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bs = new byte[is.available()];
        int len;
        while ((len = is.read(bs)) != -1) {
            baos.write(bs, 0, len);
        }
        is.close();
        String fileName = name == null ? resource.getFilename() : name;
        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }
        String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
        response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
        response.setContentType("application/octet-stream");
        response.setHeader("eva-opera-type", "download");
        response.setHeader("eva-download-filename", encodeFileName);
        response.getOutputStream().write(bs);
    }
}
